package com.z.blog.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.z.base.vo.PageVo;
import com.z.base.web.BaseController;
import com.z.blog.entity.Blog;
import com.z.blog.service.IBlogService;
import com.z.blog.service.ITagService;
import com.z.blog.service.ITypeService;
import com.z.blog.utils.MarkdownUtils;
import com.z.utils.ImageBase64Converter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/blog")
public class BlogController extends BaseController {

    @Autowired
    private IBlogService blogService;
    @Autowired
    private ITypeService typeService;
    @Autowired
    private ITagService tagService;

    @GetMapping({"index", "/", ""})
    public String indexPage(){
        return "blog/index";
    }

    @GetMapping("article")
    public String articlePage(@ModelAttribute Blog blog, String s, PageVo pageVo, Model model) {
        blog.setPublished(1);
        PageInfo<Blog> pageInfo = null;
        blog.setPublished(1);
        if(StringUtils.isEmpty(s)){
            pageInfo = blogService.selectBlogPage(blog, pageVo);
        }else {
            blog.setTitle(s);
            blog.setDescription(s);
            blog.setContent(s);
            pageInfo = blogService.selectBlogListByS(blog, pageVo);
        }
        pageInfo.getList().forEach(o -> o.setUrl(ImageBase64Converter.convertFileToBase64(o.getFirstPicture())));
        model.addAttribute("page", pageInfo);
        model.addAttribute("types", typeService.listTypeTop(5));
        model.addAttribute("hotBlogs", blogService.listHotBlogTop(5));
        model.addAttribute("recommendBlogs", blogService.listRecommendBlogTop(5));
        return "blog/article";
    }

    @GetMapping("/message")
    public String messagePage(){
        return "blog/message";
    }

    @GetMapping("read/{id}")
    public String readPage(@PathVariable String id, Model m){
        Blog blog = blogService.getById(id);
        blog.setViews(blog.getViews() + 1);
        blogService.updateViews(blog);
        blog.setTypeName(typeService.getById(blog.getTypeId()).getName());
        blog.setTags(tagService.getTagsByBlogId(Long.parseLong(id)));
        blog.setContent(MarkdownUtils.markdownToHtmlExtensions(blog.getContent()));
        m.addAttribute("blog", blog);
        return "blog/read";
    }
}
